<template>
  <div class="work-order-detail">
    <el-page-header @back="goBack" :title="'返回'" :content="'保洁工单 #' + workOrder.id" />
    
    <el-card class="detail-card" v-loading="loading">
      <template #header>
        <div class="card-header">
          <span>保洁工单详情</span>
          <el-tag :type="getStatusType(workOrder.status)">{{ workOrder.status }}</el-tag>
        </div>
      </template>
      
      <el-descriptions :column="2" border>
        <el-descriptions-item label="工单编号">{{ workOrder.id }}</el-descriptions-item>
        <el-descriptions-item label="申请时间">{{ workOrder.application_time }}</el-descriptions-item>
        <el-descriptions-item label="服务日期">{{ workOrder.expected_service_date }}</el-descriptions-item>
        <el-descriptions-item label="服务时间段">{{ workOrder.expected_time_slot || '全天' }}</el-descriptions-item>
        <el-descriptions-item label="服务地点">{{ workOrder.address }}</el-descriptions-item>
        <el-descriptions-item label="联系人">{{ workOrder.contact_name }}</el-descriptions-item>
        <el-descriptions-item label="联系电话">{{ workOrder.contact_phone }}</el-descriptions-item>
        <el-descriptions-item label="优先级">
          <el-tag :type="getPriorityType(workOrder.priority)">{{ workOrder.priority }}</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="房间面积" v-if="workOrder.room_area">{{ workOrder.room_area }} 平方米</el-descriptions-item>
        <el-descriptions-item label="保洁类型" v-if="workOrder.cleaning_type">{{ workOrder.cleaning_type }}</el-descriptions-item>
      </el-descriptions>
      
      <div class="detail-section" v-if="workOrder.special_requirements">
        <div class="section-title">特殊要求</div>
        <div class="detail-content">{{ workOrder.special_requirements }}</div>
      </div>

      <div class="detail-section" v-if="workOrder.user_remarks">
        <div class="section-title">用户备注</div>
        <div class="detail-content">{{ workOrder.user_remarks }}</div>
      </div>
      
      <div class="detail-section" v-if="workOrder.media_urls && workOrder.media_urls.length > 0">
        <div class="section-title">相关图片</div>
        <div class="image-list">
          <el-image 
            v-for="(img, index) in workOrder.media_urls" 
            :key="index"
            :src="img" 
            :preview-src-list="workOrder.media_urls"
            fit="cover"
            class="detail-image" />
        </div>
      </div>

      <!-- 服务记录 -->
      <div class="detail-section" v-if="workOrder.service_records && workOrder.service_records.length > 0">
        <div class="section-title">服务记录</div>
        <el-timeline>
          <el-timeline-item
            v-for="(record, index) in workOrder.service_records"
            :key="index"
            :timestamp="record.created_at"
            :type="getTimelineItemType(record.status)">
            <div class="timeline-content">
              <div class="timeline-title">{{ record.status }}</div>
              <div class="timeline-description">{{ record.content }}</div>
              <div class="timeline-images" v-if="record.images && record.images.length > 0">
                <el-image 
                  v-for="(img, imgIndex) in record.images" 
                  :key="imgIndex"
                  :src="img" 
                  :preview-src-list="record.images"
                  fit="cover"
                  class="timeline-image" />
              </div>
            </div>
          </el-timeline-item>
        </el-timeline>
      </div>
      
      <div class="action-section" v-if="showActionButtons">
        <el-button 
          type="primary" 
          :disabled="!canAccept" 
          @click="handleAccept">接单</el-button>
        <el-button 
          type="warning" 
          :disabled="!canStartService" 
          @click="handleStartService">开始服务</el-button>
        <el-button 
          type="success" 
          :disabled="!canComplete" 
          @click="showCompleteDialog = true">完成工单</el-button>
      </div>
    </el-card>
    
    <!-- 完成工单对话框 -->
    <el-dialog
      title="完成保洁工单"
      v-model="showCompleteDialog"
      width="500px">
      <el-form :model="completeForm" label-width="100px">
        <el-form-item label="服务结果">
          <el-input 
            type="textarea" 
            v-model="completeForm.result" 
            rows="4"
            placeholder="请输入保洁服务结果描述" />
        </el-form-item>
        <el-form-item label="完成照片">
          <el-upload
            class="upload-demo"
            action="#"
            :auto-upload="false"
            :on-change="handleFileChange"
            list-type="picture-card">
            <el-icon><Plus /></el-icon>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showCompleteDialog = false">取消</el-button>
          <el-button type="primary" @click="handleComplete">确认完成</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { cleaningService } from '@/api/tasks'

export default {
  name: 'CleaningOrderDetail',
  components: {
    Plus
  },
  setup() {
    const route = useRoute()
    const router = useRouter()
    const loading = ref(true)
    const workOrder = ref({})
    const showCompleteDialog = ref(false)
    const completeForm = ref({
      result: '',
      images: []
    })
    
    // 根据工单状态判断是否显示操作按钮
    const showActionButtons = computed(() => {
      return ['待受理', '已受理', '服务中'].includes(workOrder.value.status)
    })
    
    // 判断是否可以接单
    const canAccept = computed(() => {
      return workOrder.value.status === '待受理'
    })

    // 判断是否可以开始服务
    const canStartService = computed(() => {
      return workOrder.value.status === '已受理'
    })
    
    // 判断是否可以完成工单
    const canComplete = computed(() => {
      return workOrder.value.status === '服务中'
    })
    
    // 获取工单详情
    const fetchWorkOrderDetail = async () => {
      loading.value = true
      try {
        // 从路由参数中获取工单ID
        const id = route.params.id
        
        if (!id) {
          ElMessage.error('工单ID参数缺失')
          router.push('/staff/cleaning/dashboard')
          return
        }
        
        // 调用API获取工单详情
        const response = await cleaningService.getDetail(id)
        
        if (response.data && response.data.code === 200) {
          workOrder.value = response.data.data
          
          // 解析媒体URL
          if (workOrder.value.media_urls && typeof workOrder.value.media_urls === 'string') {
            try {
              workOrder.value.media_urls = JSON.parse(workOrder.value.media_urls)
            } catch (e) {
              workOrder.value.media_urls = []
            }
          }

          // 处理服务记录
          if (workOrder.value.service_records && typeof workOrder.value.service_records === 'string') {
            try {
              workOrder.value.service_records = JSON.parse(workOrder.value.service_records)
            } catch (e) {
              workOrder.value.service_records = []
            }
          } else if (!workOrder.value.service_records) {
            workOrder.value.service_records = []
          }
        } else {
          ElMessage.error('获取工单详情失败')
        }
        
        loading.value = false
      } catch (error) {
        console.error('获取工单详情失败', error)
        ElMessage.error('获取工单详情失败')
        loading.value = false
      }
    }
    
    // 返回上一页
    const goBack = () => {
      router.back()
    }
    
    // 获取状态标签类型
    const getStatusType = (status) => {
      const statusMap = {
        '待受理': 'info',
        '已受理': 'warning',
        '服务中': 'warning',
        '已完成': 'success',
        '已评价': 'success',
        '已取消': 'danger'
      }
      return statusMap[status] || ''
    }
    
    // 获取优先级标签类型
    const getPriorityType = (priority) => {
      const priorityMap = {
        '高': 'danger',
        '中': 'warning',
        '低': 'info'
      }
      return priorityMap[priority] || ''
    }

    // 获取时间轴项目类型
    const getTimelineItemType = (status) => {
      const typeMap = {
        '已受理': 'warning',
        '服务中': 'primary',
        '已完成': 'success',
        '已评价': 'success',
        '已取消': 'danger'
      }
      return typeMap[status] || 'info'
    }
    
    // 处理接单
    const handleAccept = async () => {
      try {
        // 调用API接单
        const response = await cleaningService.updateStatus(workOrder.value.id, '已受理')
        
        if (response.data && response.data.code === 200) {
          workOrder.value.status = '已受理'
          ElMessage.success('接单成功')
          
          // 添加服务记录
          await addServiceRecord('已受理', '保洁工单已接受', [])
          
          // 重新加载工单详情
          fetchWorkOrderDetail()
        } else {
          ElMessage.error(response.data?.message || '接单失败')
        }
      } catch (error) {
        console.error('接单失败', error)
        ElMessage.error('接单失败')
      }
    }

    // 开始服务
    const handleStartService = async () => {
      try {
        // 调用API开始服务
        const response = await cleaningService.updateStatus(workOrder.value.id, '服务中')
        
        if (response.data && response.data.code === 200) {
          workOrder.value.status = '服务中'
          ElMessage.success('已开始服务')
          
          // 添加服务记录
          await addServiceRecord('服务中', '开始提供保洁服务', [])
          
          // 重新加载工单详情
          fetchWorkOrderDetail()
        } else {
          ElMessage.error(response.data?.message || '开始服务失败')
        }
      } catch (error) {
        console.error('开始服务失败', error)
        ElMessage.error('开始服务失败')
      }
    }
    
    // 处理文件上传
    const handleFileChange = (file) => {
      completeForm.value.images.push(file.raw)
    }
    
    // 添加服务记录
    const addServiceRecord = async (status, content, images = []) => {
      try {
        await cleaningService.addRecord(
          workOrder.value.id,
          content,
          images
        )
        return true
      } catch (error) {
        console.error('添加服务记录失败', error)
        ElMessage.warning('添加服务记录失败，但状态已更新')
        return false
      }
    }
    
    // 处理完成工单
    const handleComplete = async () => {
      if (!completeForm.value.result.trim()) {
        ElMessage.warning('请输入服务结果描述')
        return
      }
      
      try {
        // 调用API完成工单
        const response = await cleaningService.updateStatus(workOrder.value.id, '已完成')
        
        if (response.data && response.data.code === 200) {
          // 添加处理记录
          await addServiceRecord(
            '已完成',
            completeForm.value.result,
            completeForm.value.images
          )
          
          workOrder.value.status = '已完成'
          showCompleteDialog.value = false
          ElMessage.success('工单已完成')
          
          // 重新加载工单详情
          fetchWorkOrderDetail()
        } else {
          ElMessage.error(response.data?.message || '完成工单失败')
        }
      } catch (error) {
        console.error('完成工单失败', error)
        ElMessage.error('完成工单失败')
      }
    }
    
    onMounted(() => {
      fetchWorkOrderDetail()
    })
    
    return {
      loading,
      workOrder,
      showActionButtons,
      canAccept,
      canStartService,
      canComplete,
      showCompleteDialog,
      completeForm,
      goBack,
      getStatusType,
      getPriorityType,
      getTimelineItemType,
      handleAccept,
      handleStartService,
      handleFileChange,
      handleComplete
    }
  }
}
</script>

<style scoped>
.work-order-detail {
  padding: 20px;
}

.detail-card {
  margin-top: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.detail-section {
  margin-top: 20px;
}

.section-title {
  font-weight: bold;
  margin-bottom: 10px;
  border-left: 4px solid #67C23A;
  padding-left: 10px;
}

.detail-content {
  padding: 10px;
  background-color: #f5f7fa;
  border-radius: 4px;
  line-height: 1.6;
}

.image-list {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.detail-image {
  width: 100px;
  height: 100px;
  border-radius: 4px;
}

.action-section {
  margin-top: 30px;
  display: flex;
  justify-content: center;
  gap: 20px;
}

.timeline-content {
  padding: 8px 0;
}

.timeline-title {
  font-weight: bold;
  margin-bottom: 5px;
  color: #67C23A;
}

.timeline-description {
  color: #606266;
  margin-bottom: 10px;
}

.timeline-images {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.timeline-image {
  width: 80px;
  height: 80px;
  border-radius: 4px;
}
</style> 